package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	idworker "github.com/gitstliu/go-id-worker"
	"math/rand"
	"net/http"
	"src/global"
	"strings"
	"time"
)

type Common struct {
}

// Forwarded-For 字段获取到用户的 IP 地址
func (c *Common) GetIP(r *http.Request) string {
	ip := r.Header.Get("X-Real-IP")
	if ip == "" {
		ip = r.Header.Get("X-Forwarded-For")
		if ip == "" {
			ip = r.RemoteAddr
		}
	}
	sep := ":"
	return strings.Split(ip, sep)[0]
}

// // IP 地址转换为整数进行比较
//
//	func ipToint(ip string) uint32 {
//		ipInt := net.ParseIP(ip).To4()
//		return binary.BigEndian.Uint32(ipInt)
//	}
//
// ip 请求token授权连续失败 禁止链接
func (c *Common) TokenIpWall(ip string) bool {
	timep := time.Now().Unix()

	myGlobal := global.Ws_
	//白名单验证
	ipWhite := myGlobal.IpWhitelist
	for _, s := range ipWhite {
		if ip == s {
			return true
		}

	}

	blackCfg := myGlobal.IpBlacklistCfg
	failtoken := myGlobal.FailToken[ip]
	if failtoken.LastTimep < timep {
		//失败次数超过5次
		if failtoken.FailNum > blackCfg.FailMaxNum {
			return false
		}
		failtoken.FailNum++
	}
	failtoken.LastTimep = timep + blackCfg.FailIntervalTime
	global.Ws_.FailToken[ip] = failtoken
	return true
}
func (c *Common) Md5(s string) string {
	m := md5.New()
	m.Write([]byte(s))
	//fmt.Println(hex.EncodeToString(m.Sum(nil)))
	return hex.EncodeToString(m.Sum(nil))
}
func (c *Common) RandString(n int) string {
	var letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	b := make([]byte, n)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return string(b)
}
func (c *Common) MakeID() int64 {
	currWoker := &idworker.IdWorker{}
	currWoker.InitIdWorker(1000, 1)
	newID, err := currWoker.NextId()
	if err == nil {
		fmt.Println(newID)
		return 0
	}
	return newID
}
